﻿var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = 'login';
}
$(document).ready(function () {
    //alert("userId"+readCookie("userId"));

    // Get Info User Login
    $.ajax({
        url: gb_servicePath + '/authenticateduser/ID/' + userId + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var admin = data.ReturnData;
                $('#p_first_last span').html(admin.FirstName + ' ' + admin.LastName);
                $('#p_phone_number span').html(admin.PhoneNumber);
                $('#p_username span').html(admin.UserName);
                $('#p_time_zone span').html(admin.TimeZoneID);
                if ((admin.UserRoles != null) && (admin.UserRoles[0] != null) && admin.UserRoles[0].RoleType == "2") {
                    $('.content_top .i_edit').attr('href', '../Profile/ProfileAdmin?ref=' + getCurrentPage());
                    window.location.href = 'SuperAdminDash';
                }
                if (admin.UserRoles[0].RoleType == "1" || admin.UserRoles[0].RoleType == "3" || admin.UserRoles[0].RoleType == "4") {
                    $('.content_top .i_edit').attr('href', '../Profile/EditProfile?ref=' + getCurrentPage());
                }
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in authenticateduser/list/summary.json ->" + xerror);
            }
        }
    });

    // Get List Time Zone
    function getListTimeZone() {
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                                $(".select_time").find(".customStyleSelectBoxInner").html(val.Timezone.Name);
                            } else {
                                var o = $("<option name='" + val.Timezone.Id + "' id='tz" + val.Timezone.Id + "' value='" + val.Timezone.Name + "' >" + val.Timezone.Name + "</option>");
                            }
                            if ($("#tz" + val.Timezone.Id).length == 0) {
                                $("#timezone_selection").find("select").append(o);
                            }
                        });
                    }
                });
    }


    function getListEnterprise(companyControlId, brandControlId) {
        $.getJSON(gb_servicePath + '/enterprise/list.json',
                function (json1) {
                    $(companyControlId).find("select").children().remove().end();
                    $(companyControlId).find(".customStyleSelectBoxInner").html("");
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            if (i == 0) {
                                var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                                $(companyControlId).find(".customStyleSelectBoxInner").html(val.Name);
                                getListBrand(val.Id, brandControlId);
                            } else {
                                var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                            }
                            $(companyControlId).find("select").append(o);
                        });
                    };
                    //$("#enterpriseList").clone().appendTo("#enterpriseListESA");                    
                });
    };

    function getListBrand(companyValue, controlId) {
        $.getJSON(gb_servicePath + '/brand/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $(controlId).find("select").children().remove().end();
                        $(controlId).find(".customStyleSelectBoxInner").html("");
                        var setSelectedItem = false;
                        $.each(json1.ReturnData, function (i, val) {
                            if (val.Company.Id == companyValue) {
                                if (!setSelectedItem) {
                                    var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                                    $(controlId).find(".customStyleSelectBoxInner").html(val.Name);
                                    setSelectedItem = true;
                                } else {
                                    var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
                                }

                                $(controlId).find("select").append(o);
                            };
                        });
                    }
                    //$("#brandList").clone().appendTo("#brandListESA");
                });
    };

    //Refill data for list brand if enterprise seleciton changed
    $("#sltEnp").change(function () {
        getListBrand($(this).children(":selected").attr("id"), "#brandList");

        //        $("select option:selected").each(function () {
        //            getListBrand($(this).val());
        //        });
    });

    //Build Enterprise to POST
    function buildEnterprise() {
        var enterprise = new Object();
        enterprise.name = $('#txt_name_enterprise').val();
        enterprise.description = '';
        return enterprise;
    }
    //Create Enterprise
    $('#btn_add_enterprise').click(function () {
        if ($("#txt_name_enterprise").val()) {
            $("#enterprise_name_label").css('color', '#595959');
            var enterprise = buildEnterprise();
            $.ajax({
                url: gb_servicePath + "/enterprise/create.json",
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(enterprise),
                "dataType": 'json',
                success: function (data) {
                    //window.location.href = '../SuperAdminDask';
                    //getListEnterprise($("#sltEnp").children(":selected").attr("id"), "#brandList");
                    getListEnterprise();
                    $("#txt_name_enterprise").val("");
                },
                error: function (jqXHR, textStatus) {
                    alert("Error in GEMAPI/enterprise/create.json");
                    alert(enterprise);
                }

            });
        } else {
            if ($("#txt_name_enterprise").val() == '') {
                $("#enterprise_name_label").css('color', 'red');
            } else {
                $("#enterprise_name_label").css('color', '#595959');
            }
        }
    });

    //Build Brand to POST
    function buildBrand() {
        var brand = new Object();
        brand.name = $('#brand_name').val();
        brand.description = $('#brand_description').val();
        brand.pocid = "1"; // unkown meaning field
        brand.enterpriseid = $("#sltEnp").children(":selected").attr("id"); // unkown meaning field
        return brand;
    }
    //Create brand
    $('#brand_add').click(function () {
        if ($("#brand_name").val() && $("#brand_description").val()) {
            $("#brand_name_label").css('color', '#595959');
            $("#brand_desc_label").css('color', '#595959');
            var brand = buildBrand();
            $.ajax({
                url: gb_servicePath + "/brand/create.json",
                crossDomain: "true",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: JSON.stringify(brand),
                "dataType": 'json',
                success: function (data) {
                    //window.location.href = '../SuperAdminDask';
                    //getListBrand($("#sltBrand").children(":selected").attr("id"), "#brandList");
                    getListBrand($('#sltEnp').children(":selected").attr("id"), "#brandList");
                    $("#brand_name").val("");
                    $("#brand_description").val("");
                },
                error: function (jqXHR, textStatus) {
                    alert("Error in GEMAPI/brand/create.json");
                    alert(brand);
                }

            });
        } else {
            if ($("#brand_name").val() == '') {
                $("#brand_name_label").css('color', 'red');
            } else {
                $("#brand_name_label").css('color', '#595959');
            }
            if ($("#brand_description").val() == '') {
                $("#brand_desc_label").css('color', 'red');
            } else {
                $("#brand_desc_label").css('color', '#595959');
            }
        }
    });

    /*All function for Admin List */
    var arrData = new Array(); // all infomation get from service
    var selectedRowKey = ""; // row's id is current selected in list 

    // Admin Dask List view
    $('.form_rows-border').find('img').css('visibility', 'hidden');
    // Json: Get Admin List
    function GetListAdmin() {
        arrData.splice(0, arrData.length);
        $.ajax({
            url: gb_servicePath + '/authenticateduser/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: "",
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $(".list_row_users").find("img").hide();
                    $(".list_row_users .rows_users").show();
                    $.each(data.ReturnData, function (i, val) {
                        var o = new Object();
                        //Id
                        o.id = val.Id;
                        //Enterprise 
                        o.enterprise = "Enterprise Name";
                        //Brand
                        o.brand = "Brand Name";
                        //Role 
                        if (val.UserRoles != null && val.UserRoles.length > 0) {
                            for (i = 0; i < val.UserRoles.length; i++) {
                                if (i + 1 == val.UserRoles.length) { // Last item
                                    o.role = val.UserRoles[i].Name;
                                } else {
                                    o.role = val.UserRoles[i].Name + "; ";
                                }
                            }

                        } else {
                            o.role = ""; // Not has any role
                        }
                        //Status
                        if (val.ApprovalStatus == 1) {
                            o.status = "true";
                        }
                        else {
                            o.status = "false";
                        }
                        //Name
                        o.name = val.LastName + ", " + val.FirstName;
                        //Campaign
                        o.campaign = "Campaign Name";
                        //o.campaign = getCampaignName(val.Id);

                        //Email
                        o.email = val.EmailAddress;

                        //Username
                        o.username = val.UserName;
                        arrData.push(o);
                    });
                    // Call bind Data function to List
                    bindData();
                    SortAdminFilter("enterprise", 1);
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in authenticateduser/list/Summary/list.json ->" + xerror);
                }
            }
        });
    }
    // End Json: Get Admin List
    /*getCampaignName(id){
    $.ajax({
    url: gb_servicePath + '/authenticateduser/ID/' + id + '.json',
    crossDomain: "true",
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    traditional: true,
    data: "",
    dataType: 'json',
    success: function (data) {
    if (data.StatusCode == 200) {
    //return data.ReturnData.
    }
    error: function (jqXHR, textStatus, xerror) {
    if (isBug) {
    alert("Error in authenticateduser/ID ->" + xerror);
    }
    }
    }
    }*/
    // Bind Data
    function bindData() {
        $(".list_row_users").find(".rows_users").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#rows_users_temp").clone();
            $(o).attr("id", arrData[i].id);
            if (i % 2 == 1) {
                $(o).addClass("users_alt");
            }
            $(o).removeClass("item_temp");
            $(o).find(".col_enterprise").html(arrData[i].enterprise);
            $(o).find(".col_brand").html(arrData[i].brand);
            $(o).find(".col_role").html(arrData[i].role);
            if (arrData[i].status == "true") {
                $(o).find(".col_status").html('Active');
            } else {
                $(o).find(".col_status").html('Inactive');
            }
            $(o).find(".colo_name").html(arrData[i].name);
            $(o).find(".colo_campaign").html(arrData[i].campaign);
            $(o).find(".colo_email").html(arrData[i].email);
            $(o).find(".col_username").html(arrData[i].username);

            if (selectedRowKey == arrData[i].id.toString()) {
                $(o).addClass('rows_user_hover');
                $(o).find('.bar').removeClass("hide");
            }
            if (arrData[i].role != 'SuperAdmin') {
                $(o).addClass("inactive rows_users_disable").removeClass('rows_users_enable');
                //$(o).removeClass("rows_users");
            }
            if ($(".list_row_users").find(".jspPane").size() == 0) {
                $(".list_row_users").append(o);
            } else {
                $(".list_row_users").find(".jspPane").append(o);
            }
        }

        /*$('.rows_users').click(function () {
        selectedRowKey = $(this).attr("id");
        alert(1);
        alert(selectedRowKey);
        $('.rows_users').removeClass('rows_user_hover');
        $(this).addClass('rows_user_hover');
        $('.bar').addClass('hide');
        $(this).find('.bar').removeClass('hide');
        $('.list_row_users').jScrollPane({ animateScroll: true });

        $('.box_super_admin').addClass('hide');
        $('#view_super_admin').removeClass('hide');
        $('.btn_close').click(function (e) {
        $("#view_super_admin").addClass('hide');
        return false;
        });
        });*/

        //close button
        $('.btn_close').click(function (e) {
            $("#view_super_admin").addClass('hide');
            $('.list_row_users').find('.rows_users').removeClass('rows_user_hover');
            $('.list_row_users').find('.bar').addClass('hide');
            $('.list_row_users').jScrollPane({ animateScroll: true });
            return false;
        });

        $('.list_row_users').jScrollPane({ animateScroll: true });
    }
    // End Bind Data

    // Function Sort Admin
    function SortAdminFilter(str, index) {
        //$.fancybox.close();

        arrData = arrData.objSort(str, index);
        $(".list_row_users").find(".rows_users").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#rows_users_temp").clone();
            $(o).attr("id", arrData[i].id);
            if (i % 2 == 1) {
                $(o).addClass("users_alt");
            }
            $(o).removeClass("item_temp");
            $(o).find(".col_enterprise").html(arrData[i].enterprise);
            $(o).find(".col_brand").html(arrData[i].brand);
            $(o).find(".col_role").html(arrData[i].role);
            if (arrData[i].status == "true") {
                $(o).find(".col_status").html('Active');
            } else {
                $(o).find(".col_status").html('Inactive');
            }
            $(o).find(".colo_name").html(arrData[i].name);
            $(o).find(".colo_campaign").html(arrData[i].campaign);
            $(o).find(".colo_email").html(arrData[i].email);
            $(o).find(".col_username").html(arrData[i].username);

            if (!$('#view_super_admin').hasClass('hide')) {
                if (selectedRowKey == arrData[i].id.toString()) {
                    $(o).addClass('rows_user_hover');
                    $(o).find('.bar').removeClass("hide");
                }
            }
            if (arrData[i].role != 'SuperAdmin') {
                $(o).addClass("inactive rows_users_disable").removeClass('rows_users_enable');
                //$(o).removeClass("rows_users");
            }
            if ($(".list_row_users").find(".jspPane").size() == 0) {
                $(".list_row_users").append(o);
            } else {
                $(".list_row_users").find(".jspPane").append(o);
            }
        }



        $('.rows_users.rows_users_enable').click(function () {

            selectedRowKey = $(this).attr("id");
            //alert(2);
            //alert(selectedRowKey);
            $('.rows_users').removeClass('rows_user_hover');
            $(this).addClass('rows_user_hover');
            $('.bar').addClass('hide');
            $(this).find('.bar').removeClass('hide');
            $('.list_row_users').jScrollPane({ animateScroll: true });

            //get Admin detail
            $.ajax({
                url: gb_servicePath + '/authenticateduser/ID/' + selectedRowKey + '.json',
                crossDomain: "true",
                type: "GET",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: "",
                dataType: 'json',
                success: function (data) {
                    if (data.StatusCode == 200) {
                        var admin = data.ReturnData;
                        var o = $('#view_super_admin');
                        $(o).find('#enterprise_sum').html('Enterprise Name');
                        $(o).find('#name_sum').html('Brand Name <br /> Brand Description');
                        $(o).find('#first_name_sum').html(admin.FirstName);
                        $(o).find('#last_name_sum').html(admin.LastName);
                        $(o).find('#campaign_name_sum').html('Campaign Name');
                        $(o).find('#email_sum').html(admin.EmailAddress);
                        $(o).find('#phone_sum').html(admin.PhoneNumber);
                        $(o).find('#username_sum').html(admin.UserName);
                        $(o).find('#timezone_sum').html(admin.TimeZoneID);
                        $(".wrapper2").append(o);
                        $('#view_super_admin_temp').hide();
                        $('.btn_close').click(function (e) {
                            $("#view_super_admin").addClass('hide');
                            $('.list_row_users').find('.rows_users').removeClass('rows_user_hover');
                            $('.list_row_users').find('.bar').addClass('hide');
                            $('.list_row_users').jScrollPane({ animateScroll: true });
                            return false;
                        });
                    }
                },
                error: function (jqXHR, textStatus, xerror) {
                    if (isBug) {
                        alert("Error in authenticateduser/list/summary.json ->" + xerror);
                    }
                }
            });
            /*if (!$('#edit_super_admin').hasClass('hide')) {
            $('#view_super_admin').addClass('hide');
            return false;
            }*/
            $('.box_super_admin').addClass('hide');

            $('#view_super_admin').removeClass('hide');

        });
        $('.btn_close').click(function (e) {
            $("#view_super_admin").addClass('hide');
            $('.list_row_users').find('.rows_users').removeClass('rows_user_hover');
            $('.list_row_users').find('.bar').addClass('hide');
            $('.list_row_users').jScrollPane({ animateScroll: true });
            return false;
        });
        $('.list_row_users').jScrollPane({ animateScroll: true });
    }
    // End Function Sort Admin
    // Bind event click Sort By Enterprise
    $("#btSortEnterprise").find("img").css("visibility", "hidden");
    $("#btSortEnterprise").click(function () {
        SortAdminFilter("enterprise", -1 * parseInt($("#btSortEnterprise").attr("sort")));
        $("#btSortEnterprise").attr("sort", -1 * parseInt($("#btSortEnterprise").attr("sort")));

        $("#btSortEnterprise").find("img").css("visibility", "visible");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortEnterprise").attr("sort") == 1) {
            $("#btSortEnterprise").find("img").rotate(180);
        } else {
            $("#btSortEnterprise").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Enterprise
    // Bind event click Sort By Brand
    $("#btSortBrand").find("img").css("visibility", "hidden");
    $("#btSortBrand").click(function () {
        SortAdminFilter("brand", -1 * parseInt($("#btSortBrand").attr("sort")));
        $("#btSortBrand").attr("sort", -1 * parseInt($("#btSortBrand").attr("sort")));

        $("#btSortBrand").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortBrand").attr("sort") == 1) {
            $("#btSortBrand").find("img").rotate(180);
        } else {
            $("#btSortBrand").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Brand
    // Bind event click Sort By Role
    $("#btSortRole").find("img").css("visibility", "hidden");
    $("#btSortRole").click(function () {
        SortAdminFilter("role", -1 * parseInt($("#btSortRole").attr("sort")));
        $("#btSortRole").attr("sort", -1 * parseInt($("#btSortRole").attr("sort")));

        $("#btSortRole").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortRole").attr("sort") == 1) {
            $("#btSortRole").find("img").rotate(180);
        } else {
            $("#btSortRole").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Role
    // Bind event click Sort By Status
    $("#btSortStatus").find("img").css("visibility", "hidden");
    $("#btSortStatus").click(function () {
        SortAdminFilter("status", -1 * parseInt($("#btSortStatus").attr("sort")));
        $("#btSortStatus").attr("sort", -1 * parseInt($("#btSortStatus").attr("sort")));

        $("#btSortStatus").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortStatus").attr("sort") == 1) {
            $("#btSortStatus").find("img").rotate(180);
        } else {
            $("#btSortStatus").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Status    
    // Bind event click Sort By Name
    $("#btSortName").find("img").css("visibility", "hidden");
    $("#btSortName").click(function () {
        SortAdminFilter("name", -1 * parseInt($("#btSortName").attr("sort")));
        $("#btSortName").attr("sort", -1 * parseInt($("#btSortName").attr("sort")));

        $("#btSortName").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortName").attr("sort") == 1) {
            $("#btSortName").find("img").rotate(180);
        } else {
            $("#btSortName").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Name

    // Bind event click Sort By Campaign
    $("#btSortCampaign").find("img").css("visibility", "hidden");
    $("#btSortCampaign").click(function () {
        SortAdminFilter("campaign", -1 * parseInt($("#btSortCampaign").attr("sort")));
        $("#btSortCampaign").attr("sort", -1 * parseInt($("#btSortCampaign").attr("sort")));

        $("#btSortCampaign").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortCampaign").attr("sort") == 1) {
            $("#btSortCampaign").find("img").rotate(180);
        } else {
            $("#btSortCampaign").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Campaign

    // Bind event click Sort By Email
    $("#btSortEmail").find("img").css("visibility", "hidden");
    $("#btSortEmail").click(function () {
        SortAdminFilter("email", -1 * parseInt($("#btSortEmail").attr("sort")));
        $("#btSortEmail").attr("sort", -1 * parseInt($("#btSortEmail").attr("sort")));

        $("#btSortEmail").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSordUsername").find("img").css("visibility", "hidden");

        if ($("#btSortEmail").attr("sort") == 1) {
            $("#btSortEmail").find("img").rotate(180);
        } else {
            $("#btSortEmail").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Email
    // Bind event click Sort By Username
    $("#btSordUsername").find("img").css("visibility", "hidden");
    $("#btSordUsername").click(function () {
        SortAdminFilter("username", -1 * parseInt($("#btSordUsername").attr("sort")));
        $("#btSordUsername").attr("sort", -1 * parseInt($("#btSordUsername").attr("sort")));

        $("#btSordUsername").find("img").css("visibility", "visible");
        $("#btSortEnterprise").find("img").css("visibility", "hidden");
        $("#btSortBrand").find("img").css("visibility", "hidden");
        $("#btSortRole").find("img").css("visibility", "hidden");
        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortStatus").find("img").css("visibility", "hidden");
        $("#btSortEmail").find("img").css("visibility", "hidden");

        if ($("#btSordUsername").attr("sort") == 1) {
            $("#btSordUsername").find("img").rotate(180);
        } else {
            $("#btSordUsername").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Username   

    //Refill data for Enterprise
    $("#ddlEnterprise").change(function () {
        getListBrand($(this).children(":selected").attr("id"), "#brandListESA");

        //        $("select option:selected").each(function () {
        //            getListBrand($(this).val());
        //        });
    });

    //    function getListEnterprise() {
    //        $.getJSON(gb_servicePath+'/enterprise/list.json',
    //                function (json1) {
    //                    $("#enterpriseList").find("select").children().remove().end();
    //                    $("#enterpriseList").find(".customStyleSelectBoxInner").html("");
    //                    if (json1.StatusCode == 200) {
    //                        $.each(json1.ReturnData, function (i, val) {
    //                            if (i == 0) {
    //                                var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
    //                                $("#enterpriseList").find(".customStyleSelectBoxInner").html(val.Name);
    //                                getListBrand(val.Id);
    //                            } else {
    //                                var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
    //                            }

    //                            $("#enterpriseList").find("select").append(o);
    //                        });
    //                    };
    //                    var lst = $("#enterpriseList").clone();
    //                    $("#enterpriseListESA") = lst;
    //                });
    //    };

    //    //Refill data for list brand if enterprise seleciton changed
    //    $("#sltEnp").change(function () {
    //        getListBrand($(this).children(":selected").attr("id"));

    //        //        $("select option:selected").each(function () {
    //        //            getListBrand($(this).val());
    //        //        });
    //    });

    //    function getListBrand(argument) {
    //        $.getJSON(gb_servicePath+'/brand/list.json',
    //                function (json1) {
    //                    if (json1.StatusCode == 200) {
    //                        $("#brandList").find("select").children().remove().end();
    //                        $("#brandList").find(".customStyleSelectBoxInner").html("");
    //                        var setSelectedItem = false;
    //                        $.each(json1.ReturnData, function (i, val) {
    //                            if (val.Company.Id == argument) {
    //                                if (!setSelectedItem) {
    //                                    var o = $("<option selected='selected' id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
    //                                    $("#brandList").find(".customStyleSelectBoxInner").html(val.Name);
    //                                    setSelectedItem = true;
    //                                } else {
    //                                    var o = $("<option id='" + val.Id + "' value='" + val.Name + "' >" + val.Name + "</option>");
    //                                }

    //                                $("#brandList").find("select").append(o);
    //                            };
    //                        });
    //                    }
    //                });
    //    };

    $('.list_row_users').jScrollPane({ animateScroll: true });
    $('.rows_users.rows_users_enable').click(function () {

        //selectedRowKey = $(this).attr("id");
        $('.rows_users').removeClass('rows_user_hover');
        $(this).addClass('rows_user_hover');
        $('.bar').addClass('hide');
        $(this).find('.bar').removeClass('hide');
        $('.list_row_users').jScrollPane({ animateScroll: true });

        $('.box_super_admin').addClass('hide');
        if (!$('#new_edit_super_admin').hasClass('hide')) {
            $('#view_super_admin').removeClass('hide');
        }
        $('.btn_close').click(function (e) {
            $("#view_super_admin").addClass('hide');
            return false;
        });
    });
    $('select.select_short3').customStyle();
    $('select.select_time').customStyle();
    function checkMail() {
        var mail = $('#txtEmail').val();
        var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (mail == '') {
            $('#title_mail').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            return false;
        }
        else if (emailReg.test(mail)) {
            // TODO: email is true
            $('#title_mail').css('color', '#595959');
            return true;
        }
        else {
            $('#title_mail').css('color', '#ff5050');
            $('#txtEmail').val('');
            $('#txtEmail').focus();
            $('#warning').html('Email address not on file');
            $('#warning').css('color', '#ff5050');
            return false;
        } //Please complete required fields
    }
    function checkEmailUniqueness(mail) {
        $.getJSON(gb_servicePath + 'authenticateduser/checkemail.json?email=' + mail,
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData) {
                            $('#warning').html('Your email address is already registered');
                            $('#warning').css('color', '#ff5050');
                            $('#title_email').css('color', '#ff5050');
                        }
                    }
                });
    }
    //check Empty
    function checkEmpty() {
        var co = true;
        var valEmp = $('#sltEnp option:selected').text();
        var calBrand = $('#sltBrand option:selected').text();
        var fisrt = $('#txtFirstName').val();
        var last = $('#txtLastName').val();
        var mail = $('#txtEmail').val();
        var phone = $('#txtPhone').val();
        if (mail == '') {
            $('#title_email').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        //        else {
        //            checkEmailUniqueness(mail);
        //            if ($('#warning').html() == 'Your email address is already registered') {
        //                co = false;
        //            }
        //        }
        if (phone == '') {
            $('#title_phone').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }

        if (last == '') {
            $('#title_lastname').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (fisrt == '') {
            $('#title_firstname').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (calBrand == 'Brand') {
            $('#title_Brand').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }
        if (valEmp == 'Enterprise') {
            $('#title_Enp').css('color', '#ff5050');
            $('#warning').html('Please complete required fields');
            $('#warning').css('color', '#ff5050');
            co = false;
        }

        return co;
    }
    //Build Account to POST
    function buildAccount() {
        var authUser = new Object();

        authUser.firstname = $('#txtFirstName').val();
        authUser.lastname = $('#txtLastName').val();
        authUser.email = $('#txtEmail').val();
        authUser.phonenumber = $('#txtPhone').val();
        authUser.timezone = $("#timezone_selection").find("option:selected").attr("name");
        if ($('#btn_Save').hasClass('new')) {
            authUser.userrole = "2"; // the role of user to be created
        }
        if ($('#btn_Save').hasClass('update')) {
            authUser.userid = $('.rows_user_hover').attr("id");
        }
        //SoliAdmin=1,
        //SuperAdmin=2,
        //Admin=3,
        //User=4,
        //Unknown=5
        //for admin and common users only
        var campaigncountry = new Object();
        campaigncountry.campaignid = "1";
        var countryids = new Array();
        countryids.push("1");
        campaigncountry.countryids = countryids;
        authUser.campaigncountrymapping = campaigncountry;

        //for super admin users only

        authUser.brandid = $('#sltBrand option:selected').attr("id");
        return authUser;
    }
    $('#btn_Save').click(function () {
        if (checkEmpty()) {
            if (!checkMail()) {
                return false;
            }
            var authUser = buildAccount();
            var url;
            var a = $('#txtEmail').val();
            if ($('#btn_Save').hasClass('new')) {
                url = "/authenticateduser/create.json";

                $.getJSON(gb_servicePath + 'authenticateduser/checkemail.json?email=' + a,
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData) {
                            $('#warning').html('Your email address is already registered');
                            $('#warning').css('color', '#ff5050');
                            $('#title_email').css('color', '#ff5050');
                        }
                        else {
                            $.ajax({
                                url: gb_servicePath + url,
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(authUser),
                                "dataType": 'json',
                                success: function (data) {
                                    $('#new_edit_super_admin').addClass('hide');
                                    resetForm();
                                    $(".list_row_users").find("img").show();
                                    $(".list_row_users .rows_users").hide();
                                    GetListAdmin();
                                },
                                error: function (jqXHR, textStatus) {
                                    alert("Error");
                                    alert(authUser);
                                }

                            });
                        }
                    }
                });

            }
            if ($('#btn_Save').hasClass('update')) {
                url = "/authenticateduser/update/" + $('.rows_user_hover').attr("id") + ".json";
                if ($('#txtEmail').val() != $('#txtEmail').attr('email')) {
                    $.getJSON(gb_servicePath + 'authenticateduser/checkemail.json?email=' + a,
                function (json1) {
                    if (json1.StatusCode == 200) {
                        if (json1.ReturnData) {
                            $('#warning').html('Your email address is already registered');
                            $('#warning').css('color', '#ff5050');
                            $('#title_email').css('color', '#ff5050');
                        }
                        else {
                            $.ajax({
                                url: gb_servicePath + url,
                                crossDomain: "true",
                                type: "POST",
                                contentType: 'application/json; charset=utf-8',
                                traditional: true,
                                data: JSON.stringify(authUser),
                                "dataType": 'json',
                                success: function (data) {
                                    $('#new_edit_super_admin').addClass('hide');
                                    resetForm();
                                    $(".list_row_users").find("img").show();
                                    $(".list_row_users .rows_users").hide();
                                    GetListAdmin();
                                },
                                error: function (jqXHR, textStatus) {
                                    alert("Error");
                                    alert(authUser);
                                }

                            });
                        }
                    }
                });
                } else {
                    $.ajax({
                        url: gb_servicePath + url,
                        crossDomain: "true",
                        type: "POST",
                        contentType: 'application/json; charset=utf-8',
                        traditional: true,
                        data: JSON.stringify(authUser),
                        "dataType": 'json',
                        success: function (data) {
                            $('#new_edit_super_admin').addClass('hide');
                            resetForm();
                            $(".list_row_users").find("img").show();
                            $(".list_row_users .rows_users").hide();
                            GetListAdmin();
                        },
                        error: function (jqXHR, textStatus) {
                            alert("Error");
                            alert(authUser);
                        }

                    });
                }
            }
            //var a = $('#warning').html();




        }


    });


    function checkMailEdit() {
        var mail = $('#txtEmail2').val();
        var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (mail == '') {
            $('#title_mail2').css('color', '#ff5050');
            $('#txtEmail2').val('');
            $('#txtEmail2').focus();
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            return false;
        }
        else if (emailReg.test(mail)) {
            // TODO: email is true
            $('#title_mail2').css('color', '#595959');
            return true;
        }
        else {
            $('#title_mail2').css('color', '#ff5050');
            $('#txtEmail2').val('');
            $('#txtEmail2').focus();
            $('#warning2').html('Email address not on file');
            $('#warning2').css('color', '#ff5050');
            return false;
        } //Please complete required fields
    }
    function checkEmptyEdit() {
        var co = true;
        var valEmp = $('#ddlEnterprise option:selected').text();
        var calBrand = $('#sltBrand2 option:selected').text();
        var fisrt = $('#txtFirstName2').val();
        var last = $('#txtLastName2').val();
        var mail = $('#txtEmail2').val();
        var phone = $('#txtPhone2').val();

        if (phone == '') {
            $('#title_phone2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (mail == '') {
            $('#title_email2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (last == '') {
            $('#title_lastname2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (fisrt == '') {
            $('#title_firstname2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (calBrand == 'Brand') {
            $('#title_Brand2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        if (valEmp == 'Enterprise') {
            $('#title_Enp2').css('color', '#ff5050');
            $('#warning2').html('Please complete required fields');
            $('#warning2').css('color', '#ff5050');
            co = false;
        }
        return co;
    }
    GetListAdmin();
    getListEnterprise("#enterpriseList", "#brandList");
    getListTimeZone();
});
function showEdit() {
    $('.box_super_admin').addClass('hide');
    resetForm();
    $('#txtFirstName').attr('readonly', 'readonly');
    $('#txtLastName').attr('readonly', 'readonly');
    selectedRowKey = $('.rows_user_hover').attr("id");
    //get Admin detail
    $.ajax({
        url: gb_servicePath + '/authenticateduser/ID/' + selectedRowKey + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var admin = data.ReturnData;
                $('#txtFirstName').val(admin.FirstName);
                $('#txtLastName').val(admin.LastName);
                $('#txtEmail').val(admin.EmailAddress);
                $('#txtEmail').attr('email',admin.EmailAddress);
                $('#txtPhone').val(admin.PhoneNumber);
                $('.tr_username').removeClass('hide');
                $('#lbl_username').html(admin.UserName);
                $('#cb_timezone option[name=' + admin.TimeZoneID + ']').attr("selected", "selected");
                $('#timezone_selection .customStyleSelectBoxInner').html($('#cb_timezone option[name=' + admin.TimeZoneID + ']').val());
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in authenticateduser/list/summary.json ->" + xerror);
            }
        }
    });
    $('#new_edit_super_admin').removeClass('hide');
    $('#view_super_admin').addClass('hide');
    $('#header_new_edit').html('Edit Super Admin');
    $('#new_edit_super_admin').removeClass('nobg');
    $('#btn_Save').removeClass('new').addClass('update');
    $('#btnCalcel').click(function (e) {
        $("#new_edit_super_admin").addClass('hide');
        return false;
    });

}
function showNewAdmin() {
    $('#txtFirstName').removeAttr('readonly');
    $('#txtLastName').removeAttr('readonly');
    $('.tr_username').addClass('hide');
    $('.box_super_admin').addClass('hide');
    $('#new_edit_super_admin').removeClass('hide');
    $('.rows_users.rows_user_hover').removeClass('rows_user_hover');
    $('.bar').addClass('hide');
    $('.list_row_users').jScrollPane({ animateScroll: true });
    $('#header_new_edit').html('New Super Admin');
    $('#new_edit_super_admin').addClass('nobg');
    $('#btn_Save').removeClass('update').addClass('new');
    $('#btnCalcel').click(function (e) {
        $("#new_edit_super_admin").addClass('hide');
        return false;
    });
    resetForm();
}
function resetForm() {
    $('#txtFirstName').val('');
    $('#txtLastName').val('');
    $('#txtEmail').val('');
    $('#txtPhone').val('');

}
        
    
